<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Power;
use App\Http\Controllers\Log;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cookie;


/**
 * 后端的接口，获取此控制器中的接口，每次都需要进行权限验证
 */

class Back extends Controller
{
  //获取背景图片
  public function getBack(Request $req){

    if(!Power::validate($req)){
      //验证未通过
      return redirect('admin/login');
    }


    $back = DB::table('background')->get();
    // dd($back);
    //替换字符串
    foreach($back as $a){
      $a->start_time = str_replace(".",":",$a->start_time."");
      $a->end_time = str_replace(".",":",$a->end_time."");
    }

    return ['code'=>200,"message"=>'获取成功','data'=>$back];
  }

  //添加背景图片或修改图片
  public function addBack(Request $req){
    $back = $req->back;
    $id = $back['id'];
    $data = [
      'name'=>$back['name'],
      'url'=>$back['url'],
      'start_time'=>$back['time'][0],
      'end_time'=>$back['time'][1],
      'created_time'=>date('Y-m-d H:i:s')
    ];

    $data['start_time'] = str_replace(":",".",$data['start_time']);
    $data['end_time'] = str_replace(":",".",$data['end_time']);

    if($id){
      //进行修改
      if(DB::table('background')->where('id',$id)->update($data)){
        return ['code'=>200,"message"=>'修改成功'];
      }else{
        return ['code'=>-1,"message"=>'修改失败'];
      }

    }else{
      if(DB::table('background')->insertGetId($data)){
        return ['code'=>200,"message"=>'添加成功'];
      }else{
        return ['code'=>-1,"message"=>'添加失败'];
      }  
    }  
    
  }

  // //编辑背景图片
  // public function setBack(Request $req){
  //   $id = $req->back_id;
  //   $back = $req->back;
  //   $data = [
  //     'name'=>$back['name'],
  //     'url'=>$back['url'],
  //     'starttime'=>$back['time'][0],
  //     'endtime'=>$back['time'][1],
  //     'created_time'=>date('Y-m-d H:i:s')
  //   ];
    
  // }

  //删除背景图片
  public function delectBack(Request $req){
    $id = $req->back_id;
    if(DB::table('background')->where('id',$id)->delete()){
      return ['code'=>200,"message"=>'删除成功'];
    }else{
      return ['code'=>-1,"message"=>'删除失败'];
    }
  }



}
